package cz.myslivec.slovicka.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;

import cz.myslivec.slovicka.entity.Lesson;

@Name("lessonDao")
@AutoCreate
public class LessonDao implements Serializable {
	private static final long serialVersionUID = -6349922983777442128L;
	
	@Logger
	Log log;
	
	@In
	private EntityManager entityManager;
	
	public Lesson get(Long id) {
		log.info("<><> lessonDao.get() {0}", id);
		
		if(id == null) {
			return null;
		}
		return entityManager.find(Lesson.class, id);
	}

	@Factory("lessonList")
	@SuppressWarnings("unchecked")
	public List<Lesson> list() {
		log.info("<><> lessonDao.list()");
		
		Query query = entityManager.createQuery("from Lesson");
		return query.getResultList();
	}
	
	public void delete(Lesson lesson) {
		Query query = entityManager.createQuery("DELETE FROM Lesson ls where ls=:lesson");
		query.setParameter("lesson", lesson);
		int sc = query.executeUpdate();
		if(sc == 1) {
			log.info("Successful deleting lesson: {0}", lesson.toString());
		} else {
			log.info("Unsuccessful deleting lesson: {0}", lesson.toString());
		} 
	}
	
}
